package com.zprmb.udzt;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.zprmb.udzt.activity.V6LoginActivity2;
import com.zprmb.udzt.http.AjaxCallBack;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.http.FinalHttp;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.util.PermissionUtils;
import com.zprmb.udzt.util.UpdateManager;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.util.VolleryUtil2;
import com.zprmb.udzt.util.VolleryUtil3;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Enumeration;

import static com.taobao.accs.ACCSManager.mContext;

/**
 * 欢迎界面
 *
 * @author shenshao
 */

public class SplashActivity extends Activity {

    private static final int PERMISSION_READ_PHONE_STATE = 1;
    private static final int PERMISSION_CALL_PHONE = 2;
    private static final int PERMISSION_EXTERNAL_STORAGE = 3;
    private static final int PERMISSION_USE_FINGERPRINT = 4;

    private static final int STATE_READ_PHONE_STATE = 101;
    private static final int STATE_CALL_PHONE = 102;
    private static final int STATE_EXTERNAL_STORAGE = 103;
    private static final int STATE_USE_FINGERPRINT = 104;

    private static final int REQUEST_UPDATE = 5;

    private static final String SHAREDPREFERENCES_NAME = "first_pref";
    private static final int GO_HOME = 1000;
    private static final int GO_GUIDE = 1001;
    private static final long SPLASH_DELAY_MILLIS = 0;
    private int delayTime = 3;// 广告4秒倒计时
    private final int UPDATE_TEAY_TIME = 103;
    private String description;// 更新内容
    private String url;// 下载链接
    private String csrf;
    private boolean forceUpdate = false;// 是否强制更新
    private Dialog dialog;
    private RelativeLayout rl;
    private TextView dTime;
    private TextView skipBtn;
    private String linkurl = "", imageurl = "";
    private RelativeLayout rl_jump;

    private boolean requestPermissionState = false;
    private boolean isPermissionDialogShow = false;
    private boolean isJumpToSetting = false;
//	private LinearLayout ll_splash;
    /**
     * 手机信息收集
     */
    private ImageView welComeImg, adImg;
    private String version;// 版本号
    private String token;// 手机串号
    private String token2;// 手机串号
    // private String SimSerialNumber;// 手机SIM卡序列号
    // private String subscriberId;
    // private String deviceSoftwareVersion;
    private String json;
    private String channel;
    private RequestQueue mQueue;
    private Bitmap bitmap;
    int appVer2 = 0;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GO_HOME:
                    goHome();
                    break;
                case GO_GUIDE:
                    goGuide();
                    initcsrf();
                    break;
                case 9:
                    Toast.makeText(SplashActivity.this, json, 1).show();
                    break;
                case 10:
                    SplashActivity.this.finish();
                    break;
                case UPDATE_TEAY_TIME:

                    if (delayTime > 0) {
//                        welComeImg.setVisibility(View.GONE);
                        rl.setVisibility(View.VISIBLE);
                        dTime.setText(delayTime + "");
                        handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
                        delayTime--;
                    } else {
                        handler.sendEmptyMessage(GO_HOME);

                    }


                    break;


                case 100:
                    if (requestPermissionState && !isJumpToSetting) {
                        checkUpdatePermission();
                    }
                    break;
            }
        }

        ;
    };
    private SharedPreferences sp;
    //    private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.USE_FINGERPRINT};
    // 打开相机请求Code，多个权限请求Code
/*private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
        , Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CALENDAR};*/
    private final int REQUEST_CODE_CAMERA = 1, REQUEST_CODE_PERMISSIONS = 2;
    private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.USE_FINGERPRINT};
    private AlertDialog alertDialog;
    private AlertDialog alertDialog2;
    private AlertDialog alertDialog1;


    @Override
    protected void onRestart() {
        super.onRestart();

        if (requestPermissionState) {
            checkUpdatePermission();
        }

    }

    //
//    private final String PERMISSION_CAMERA2 = Manifest.permission.READ_PHONE_STATE;
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        Log.e("回到", "1");

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (requestPermissionState && !isJumpToSetting) {
            isJumpToSetting = true;
        }
    }

    private final String PERMISSION_CAMERA = Manifest.permission.CAMERA;

    private Bitmap getSdBitmap(String path) {
        File mFile = new File(path);
        Bitmap bitmap;
        //若该文件存在
        if (mFile.exists()) {
//        	LogUtils.e(GestureVerifyActivity.this.this, "sd卡图片存在");
            bitmap = BitmapFactory.decodeFile(path);
            return bitmap;
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_girl);
        }
        return bitmap;
    }

    // 普通申请一个权限
    private void checkPermission() {


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(0);
        }

    }

    private void requestPermission(int permission) {

        ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);

    }

    private void requestContactPermission(String permission) {
        if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            //申请 WRITE_CONTACTS 权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE,}, 1);
//            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
        } else {
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            token = tm.getDeviceId();
            goOn();
        }
    }

    public boolean network() {
        boolean flag = false;

        //得到网络连接信息
        ConnectivityManager manager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        //去进行判断网络是否连接
        if (manager.getActiveNetworkInfo() != null) {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }

        return flag;

    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_activity);
        sp = getSharedPreferences("config", MODE_PRIVATE);

        MySharePreferenceUtil.put(SplashActivity.this, "newintentflag", "2");

        if (!network()) {
            goHome();
        } else {
            mQueue = Volley.newRequestQueue(this);
//        BbtApplication.getInstance().addActvity(this);
            sp = getSharedPreferences("config", MODE_PRIVATE);
            setImmersionStatus();
            mContext = this;

//
            requestContactPermission(Manifest.permission.READ_PHONE_STATE);
//            requestContactPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            alertDialog2 = new AlertDialog.Builder(mContext)
                    .setTitle("需要权限")
                    .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                    .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PermissionUtils.toAppSetting(mContext);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
//            MySharePreferenceUtil.put(SplashActivity.this, "intentflag", "1");
//        在第一个启动页里的onCreate()方法里面添加下面代码就可以了
            if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
                finish();
                return;
            }
        }


    }


    private void goOn() {
        BbtApplication.getInstance().addActvity(this);
        rl = (RelativeLayout) findViewById(R.id.rl_show_ad);
        welComeImg = (ImageView) findViewById(R.id.iv_welcome_img);
        adImg = (ImageView) findViewById(R.id.iv_ad_img);
        dTime = (TextView) findViewById(R.id.tv_time);
        skipBtn = (TextView) findViewById(R.id.ll_ad_skip_btn);
        rl_jump = (RelativeLayout) findViewById(R.id.rl_jump);
        rl_jump.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                goHome();
                handler.removeMessages(UPDATE_TEAY_TIME);
            }
        });

        if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
            checkDeviceHasNavigationBar(this);
        }
        initData2();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d("SplashActivity", "--> onRequestPermissionsResult:permissions = " + Arrays.toString(permissions));
        Log.d("SplashActivity", "--> onRequestPermissionsResult:grantResults = " + Arrays.toString(grantResults));
        int sum = 0;
        for (int grant : grantResults) {
            sum += grant;
        }


        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    token = tm.getDeviceId();
                    goOn();
                } else {

                    token = "";
                    goOn();

                }
                break;

            case REQUEST_UPDATE:
                if (sum >= 0) {
                    UpdateManager manager = new UpdateManager(SplashActivity.this,
                            url);
                    manager.showDownloadDialog();
                } else {
                    if (!isPermissionDialogShow)
                        showExplainDialog();
                }
                break;

        }
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog() {
        alertDialog1 = new AlertDialog.Builder(mContext)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissionState = true;
                        PermissionUtils.toAppSetting(mContext);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .create();

        if (!alertDialog1.isShowing()) {

            alertDialog1
                    .show();
            isPermissionDialogShow = true;
        }


        alertDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isPermissionDialogShow = false;
            }
        });

    }


    private void initcsrf() {
        // 这个接口返回的请求头里有3个参数，，前两个暂时写死！
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                try {

                    if (jsonObject.optInt("success") == 1) {
                        csrf = jsonObject.getJSONObject("data").optString(
                                "csrf");
                        activite();
                    } else {

                        Toast.makeText(SplashActivity.this,
                                jsonObject.optString("comment"), 0).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("appId", "bbt3.0:android");
        vollery.setHeaders("appSecret", "RH89xcYh");
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setRequestMethod(1);
        vollery.execute(this, Constant.URL + "api/csrf", "");
    }

    private void activite() {
        // TODO Auto-generated method stub
        AjaxParams params = new AjaxParams();
        params.put("deviceId", token);
        params.put("client", "android");
        params.put("platform", getMetaData(this));
        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        volleryUtil.setHeaders("csrf", csrf);
        volleryUtil.setRequestMethod(0);
        volleryUtil.execute(SplashActivity.this, Constant.URL + "/api/activateInfo?", params.toString());
        Log.e("激活", Constant.URL + "/api/activateInfo?" + params.toString());
//	    Toast.makeText(SplashActivity.this, getMetaData(this)+"",2000).show();
    }

    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null) {

            bitmap.recycle();
        }
        handler.removeCallbacksAndMessages(null);
        handler = null;
        setContentView(R.layout.viewxml);

        BbtApplication.getInstance().removeActvity(this);

    }


    /**
     * 状态栏高度
     *
     * @return
     */
    /*public int getStatusBarHeight() {
          int result = 0;
		  int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		  if (resourceId > 0) {
		      result = getResources().getDimensionPixelSize(resourceId);
		  }
		  return result;
	}*/

	/*public static int getNavigationBarHeight(Activity activity) {  
        Resources resources = activity.getResources();  
        int resourceId = resources.getIdentifier("navigation_bar_height",  
                "dimen", "android");  
        //获取NavigationBar的高度  
        int height = resources.getDimensionPixelSize(resourceId);  
        return height;  
    }  
	*/
    @SuppressLint("NewApi")
    public void checkDeviceHasNavigationBar(Context activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar  
        try {
            boolean hasMenuKey = ViewConfiguration.get(activity).hasPermanentMenuKey();
            boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (!hasMenuKey && !hasBackKey) {
                // 做任何你需要做的,这个设备有一个导航栏
                SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
                Editor editor = sp.edit();
                editor.putString("navigation", "1");
                editor.commit();
                // Toast.makeText(SplashActivity.this, "true", 0).show();
            } else {
                //	Toast.makeText(SplashActivity.this, "fals", 0).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initData2() {
        VolleryUtil2 vollery = new VolleryUtil2() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                LogUtils.e(SplashActivity.this, jsonObject.toString());
                if (jsonObject.optInt("success") == 1) {
//							Log.e("splash", jsonObject.toString());
                    Editor editor = sp.edit();
                    editor.putString("uplan_title",
                            jsonObject.optString("data"));
                    editor.commit();
                    JSONObject json1 = jsonObject.optJSONObject("data");
//							Toast.makeText(SplashActivity.this, json1.optString("linkUrl"), 2000).show();
                    if (json1 != null) {

                        linkurl = json1.optString("linkUrl");
                        imageurl = json1.optString("url");
                    } else {
                        linkurl = "";
                        imageurl = "";
                    }
                    initData1();
                } else {
                    initData1();
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                initData1();

            }
        };
        vollery.setRequestMethod(0);

        vollery.execute(this, Constant.URL
                + "api/v5/home/ads", "");
    }

    private void initData1() {
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
//				LogUtils.e(SplashActivity.this, "升级"+jsonObject.toString());
                description = jsonObject.optString("description");
                url = jsonObject.optString("url");
                forceUpdate = jsonObject.optBoolean("forceUpdate");
                version = jsonObject.optString("version");
                int intVer = Integer.parseInt(version.replace(".", ""));
//				Log.e("update", url);
                int appVer = Integer.parseInt(getAppVersion().replace(".", ""));
                appVer2 = Integer.parseInt(getAppVersion().replace(".", ""));
//				ToastUtil.showCenterToast(SplashActivity.this, forceUpdate+"");
                Log.d(appVer + "", "4444444444444444");
                if (intVer <= appVer) {
                    //没有升级dialog
//                    showUpVersionDialog(description, "http://udrmb-file.b0.upaiyun.com/apk/udrmb_1.1.7.apk", forceUpdate, version);
                    init();
                } else {
//                    showUpVersionDialog(description, "https://a.app.qq.com/o/simple.jsp?pkgname=com.zprmb.udzt&channel=0002160650432d595942&fromcase=60001", forceUpdate, version);
                    showUpVersionDialog(description, url, forceUpdate, version);
//					showUpVersionDialog("1、 全新UI风格设计，交互和体验全面升级\n2、 投资流程优化，操作更便捷\n3、 账户管理全新设计，管理资产一目了然\n4、 其他功能细节优化", url, forceUpdate, version);
//             、<a href='https://a.app.qq.com/o/simple.jsp?pkgname=com.zprmb.udzt&channel=0002160650432d595942&fromcase=60001'>修复</a>部分安卓机型开机闪退问题1。"
//                  showUpVersionDialog("1、修复部分安卓机型开机闪退问题。注：如您遇到无法安装问题，请先卸载此版本后重新安装最新版本或拨打客服热线400 0101 016\n", url, forceUpdate, version);
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setRequestMethod(0);
        vollery.execute(this, Constant.URL + "api/update", "");
    }

    private void initData() {
        AjaxParams params = new AjaxParams();
        if (token.equals("") || token == null) {
            token = "获取手机串号失败";
        } else {
            params.put("imei", token);
        }
        FinalHttp fh = new FinalHttp();
        fh.get(Constant.URL + "update", new AjaxCallBack<Object>() {
            public void onStart() {
                super.onStart();
            }

            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Toast.makeText(SplashActivity.this, "网络无法连接,请检查网络", 0).show();
                Log.e("splash=", t + "-----" + strMsg + "----" + errorNo);
            }

            public void onSuccess(Object t) {
                super.onSuccess(t);
                String json = (String) t;
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    description = jsonObject.optString("description");
                    url = jsonObject.optString("url");
                    forceUpdate = jsonObject.optBoolean("forceUpdate");
                    version = jsonObject.optString("version");
                    int intVer = Integer.parseInt(version.replace(".", ""));

                    int appVer = Integer.parseInt(getAppVersion().replace(".", ""));


                    if (intVer <= appVer) {

                        init();
                    } else {
                        showUpVersionDialog(description, url, forceUpdate, version);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private void init() {
        SharedPreferences preferences = getSharedPreferences(
                SHAREDPREFERENCES_NAME, MODE_PRIVATE);
        // 取得相应的值，如果没有该值，说明还未写入，用true作为默认值
        boolean isFirstIn = preferences.getBoolean("isFirstIn", true);
        // 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
       /* if (appVer2 == 113) {

        }*/
        if (TextUtils.isEmpty((String) MySharePreferenceUtil.get(SplashActivity.this, "guide", ""))) {
            boolean isFirstIn1 = false;
            preferences = getSharedPreferences(SHAREDPREFERENCES_NAME,
                    MODE_PRIVATE);
            Editor editor = preferences.edit();
            editor.putBoolean("isFirstIn", isFirstIn1);
            editor.commit();
            handler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS);
        } else {

            initcaptcha();
        }

      /*  if (!isFirstIn) {
            // 使用Handler的postDelayed方法，3秒后执行跳转到MainActivity

            initcaptcha();
        } else {
            boolean isFirstIn1 = false;
            preferences = getSharedPreferences(SHAREDPREFERENCES_NAME,
                    MODE_PRIVATE);
            Editor editor = preferences.edit();
            editor.putBoolean("isFirstIn", isFirstIn1);
            editor.commit();
            handler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS);
        }*/
    }

    //flag_zhiwen
    public int getisFingerPay() {
        int a = sp.getInt(getMobile() + "fingerPay", 0);
        Log.d("指纹的呢", a + "");
        return sp.getInt(getMobile() + "fingerPay", 0);


    }

    public String getMobile() {
        return sp.getString("mobile", "");
    }

    public int getisFinger() {
        return sp.getInt("finger", 0);
    }

    public SharedPreferences getShare() {
        return sp;
    }

    public int getopenfinger() {
        return sp.getInt(getMobile() + "openfinger", 0);
    }

    private void initcaptcha() {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
//			DiskCacheUtils.removeFromCache("https://rmbboximage.b0.upaiyun.com/appads0", 		BbtApplication.getInstance().imageLoader.getDiskCache());
//	        MemoryCacheUtils.removeFromCache("https://rmbboximage.b0.upaiyun.com/appads0", 		BbtApplication.getInstance().imageLoader.getMemoryCache());
//			BbtApplication.getInstance().onClearDiskClick(adImg);
//			BbtApplication.getInstance().onClearMemoryClick(adImg);
//			BbtApplication.getInstance().display("https://rmbboximage.b0.upaiyun.com/appads0", adImg);
//			handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
        BbtApplication.getInstance().imageLoader.displayImage(imageurl, adImg, new ImageLoadingListener() {

            @Override
            public void onLoadingStarted(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                // TODO Auto-generated method stub
                handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
                adImg.setImageResource(R.drawable.v6splash3);


            }

            @Override
            public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                // TODO Auto-generated method stub
                Log.e("linkurl", linkurl);
                handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
            }

            @Override
            public void onLoadingCancelled(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }
        });
        Log.e("linkurl", linkurl);
        adImg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (linkurl == null || linkurl.equals("null") || linkurl.length() <= 0) {
                    return;
                }
                handler.removeMessages(UPDATE_TEAY_TIME);
                Intent intent0 = null;
/*//                intent0 = new Intent(SplashActivity.this, WebViewActivity.class);
                intent0 = new Intent(SplashActivity.this, V6LoginActivity2.class);
                intent0.putExtra("url", linkurl + "?app=true&token=");
                intent0.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                intent0.putExtra("share", 1);
                intent0.putExtra("splash", 1);
                intent0.putExtra("titleview", 1);
                intent0.putExtra("title", "优点智投");
                startActivity(intent0);
                finish();*/

                VolleryUtil3 volleryUtil = new VolleryUtil3() {

                    @Override
                    public void onUpDate(JSONObject jsonObject) {
                        Log.d(jsonObject.toString(), "3333333333333333");

                        // TODO Auto-generated method stub
                        if (jsonObject.optInt("success") == 1) {
                            String gesture = (String) MySharePreferenceUtil.get(SplashActivity.this, "gesture", "");
                            String zhiwen = (String) MySharePreferenceUtil.get(SplashActivity.this, "zhiwendenglu", "");
                            Log.d("指纹", zhiwen);
                            MySharePreferenceUtil.put(SplashActivity.this, "intentflag", "1");
                            MySharePreferenceUtil.put(SplashActivity.this, "url", linkurl + "?app=true&token=");
                            MySharePreferenceUtil.put(SplashActivity.this, "title", "优点智投");
                            if (gesture.equals("1")) {

//                                Intent intent = new Intent(SplashActivity.this, GestureVerify_newActivity.class);
                                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                                intent.putExtra("web", 1);
                                intent.putExtra("close", 0);
                                intent.putExtra("assets", 0);

                                intent.putExtra("url", linkurl + "?app=true&token=");
                                intent.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent.putExtra("share", 1);
                                intent.putExtra("splash", 1);
                                intent.putExtra("titleview", 1);
                                intent.putExtra("title", "优点智投");
                                startActivity(intent);
                                overridePendingTransition(R.anim.fade_in_center,
                                        R.anim.fade_out_center);
                                finish();


                            } else if (gesture.equals("0") && zhiwen.equals("1")) {
//                                Intent intent = new Intent(SplashActivity.this, V6_Finger_Check_NewActivity.class);
                                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                                intent.putExtra("web", 1);
                                intent.putExtra("close", 0);
                                intent.putExtra("assets", 0);

                                intent.putExtra("url", linkurl + "?app=true&token=");
                                intent.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent.putExtra("share", 1);
                                intent.putExtra("splash", 1);
                                intent.putExtra("titleview", 1);
                                intent.putExtra("title", "优点智投");
                                startActivity(intent);
                                overridePendingTransition(R.anim.fade_in_center,
                                        R.anim.fade_out_center);
                                finish();
                            } else {
                                Intent intent0 = null;
                                Log.e("login", jsonObject.toString());
                                intent0 = new Intent(SplashActivity.this, MainActivity.class);
                                intent0.putExtra("url", linkurl + "?app=true&token=");
                                intent0.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent0.putExtra("share", 1);
                                intent0.putExtra("splash", 1);
                                intent0.putExtra("titleview", 1);
                                intent0.putExtra("title", "优点智投");
                                startActivity(intent0);
                                overridePendingTransition(R.anim.fade_in_center,
                                        R.anim.fade_out_center);
                                finish();


//                                Toast.makeText(SplashActivity.this, "33333", Toast.LENGTH_SHORT).show();
                            }




/*

                            if (getisFinger() == 1 && getopenfinger() == 1 && !getShare().getString(getMobile(), "").equals("")) {
                                Intent intent = new Intent(SplashActivity.this, GestureVerify_newActivity.class);
                                intent.putExtra("web", 1);
                                intent.putExtra("close", 0);
                                intent.putExtra("assets", 0);

                                intent.putExtra("url", linkurl + "?app=true&token=");
                                intent.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent.putExtra("share", 1);
                                intent.putExtra("splash", 1);
                                intent.putExtra("titleview", 1);
                                intent.putExtra("title", "优点智投");
                                startActivity(intent);

                            } else if (getisFinger() == 1 && getopenfinger() == 1 && getShare().getString(getMobile(), "").equals("")) {
                                Intent intent = new Intent(SplashActivity.this, V6_Finger_CheckActivity.class);
                                intent.putExtra("web", 1);
                                intent.putExtra("close", 0);
                                intent.putExtra("assets", 0);

                                intent.putExtra("url", linkurl + "?app=true&token=");
                                intent.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent.putExtra("share", 1);
                                intent.putExtra("splash", 1);
                                intent.putExtra("titleview", 1);
                                intent.putExtra("title", "优点智投");
                            } else if (!getShare().getString(getMobile(), "").equals("")) {
                                Intent intent = new Intent(SplashActivity.this, GestureVerify_newActivity.class);
                                intent.putExtra("web", 1);
                                intent.putExtra("close", 0);
                                intent.putExtra("assets", 0);

                                intent.putExtra("url", linkurl + "?app=true&token=");
                                intent.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent.putExtra("share", 1);
                                intent.putExtra("splash", 1);
                                intent.putExtra("titleview", 1);
                                intent.putExtra("title", "优点智投");
                            } else {

                            }*/


                        } else {
                            if (jsonObject.optString("comment").equals("please login")) {
                                Log.e("login","V6LoginActivity2");
                                Intent intent0 = null;
                                Log.e("login", jsonObject.toString());
                                intent0 = new Intent(SplashActivity.this, V6LoginActivity2.class);
                                intent0.putExtra("url", linkurl + "?app=true&token=");
                                intent0.putExtra("flag", 1);
//					intent2.putExtra("url", "/h5/messageCenter?app=true&token="+getToken());
                                intent0.putExtra("share", 1);
                                intent0.putExtra("splash", 1);
                                intent0.putExtra("titleview", 1);
                                intent0.putExtra("title", "优点智投");
                                startActivity(intent0);
                                finish();

                            } else {
                                Toast.makeText(SplashActivity.this, jsonObject.optString("comment"), 2000).show();
                            }
                        }

                    }

                    @Override
                    public void onError() {
                        // TODO Auto-generated method stub

                    }
                };


                volleryUtil.setHeaders("token", token);
                volleryUtil.setRequestMethod(0);
                volleryUtil.execute(SplashActivity.this, Constant.URL + "/api/v5/user/accountCenter", "");

            }
        });


    }


    private void goHome() {
        token2 = (String) MySharePreferenceUtil.get(SplashActivity.this, "mytoken", "");

    /*    try {
            token2 = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        String userId = sp.getString("userId", "");
//		ToastUtil.showCenterToast(this, "跳过");
//        Toast.makeText(this, userId + "", Toast.LENGTH_SHORT).show();
        if (TextUtils.isEmpty(userId)) {
            Log.e("login","V6LoginActivity");
            Intent intent = new Intent(SplashActivity.this, V6LoginActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_from_bottom,
                    R.anim.slide_out_to_bottom);
            handler.sendEmptyMessage(10);


        } else {
//            Toast.makeText(this, token + "", Toast.LENGTH_SHORT).show();

            VolleryUtil3 volleryUtil = new VolleryUtil3() {

                @Override
                public void onUpDate(JSONObject jsonObject) {
                    Log.d(jsonObject.toString(), "3333333333333333");

                    // TODO Auto-generated method stub
                    if (jsonObject.optInt("success") == 1) {

                        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.fade_in_center,
                                R.anim.fade_out_center);
                        handler.sendEmptyMessage(10);
                    } else {
                        if (jsonObject.optString("comment").equals("please login")) {
//						Editor ed=sha.edit();
//						ed.putInt("islogin", 0);Constant
//						ed.commit();
                            Log.e("login", jsonObject.toString());
//                            startActivity(new Intent(SplashActivity.this, V6LoginActivity.class));

                            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                            intent.putExtra("web", 1);
                            intent.putExtra("close", 0);
                            intent.putExtra("assets", 0);

                            startActivity(intent);
                            overridePendingTransition(R.anim.fade_in_center,
                                    R.anim.fade_out_center);
                        } else {
//                            Toast.makeText(MainActivity.this, jsonObject.optString("comment"), 2000).show();
                        }
                    }

                }

                @Override
                public void onError() {
                    // TODO Auto-generated method stub

                }
            };

//            Log.d("------------token", V6LoginActivity.token);
            volleryUtil.setHeaders("token", token2);
            volleryUtil.setRequestMethod(0);
            volleryUtil.execute(SplashActivity.this, Constant.URL + "/api/v5/user/accountCenter", "");


        }
    }

    private void goGuide() {
        Intent intent = new Intent(SplashActivity.this, V4GuideActivity.class);// GuideActivity
        SplashActivity.this.startActivity(intent);
        SplashActivity.this.finish();
    }

    private void showUpVersionDialog(String content, final String url,
                                     final boolean forceUpdate, String version) {
        dialog = new Dialog(SplashActivity.this);
        dialog.setCancelable(false);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(
                R.color.float_transparent)));
        window.setGravity(Gravity.CENTER);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        window.setContentView(R.layout.item_splash_upversion_dialog);
        dialog.show();
        TextView tv_upversion_dialog_content = (TextView) window
                .findViewById(R.id.tv_upversion_dialog_content);
        TextView tv_version = (TextView) window
                .findViewById(R.id.tv_version);
        ImageView tv_upversion_dialog_clean = (ImageView) window
                .findViewById(R.id.tv_upversion_dialog_clean);
        TextView tv_upversion_dialog_up = (TextView) window
                .findViewById(R.id.tv_upversion_dialog_up);
        tv_upversion_dialog_content.setText(content);
        tv_version.setText("v" + this.version);
        tv_upversion_dialog_clean.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (dialog != null) {
                    dialog.cancel();
                }
                if (forceUpdate) {
                    SplashActivity.this.finish();
                    //android.os.Process.killProcess(android.os.Process.myPid());
                } else {
                    init();
                }
            }
        });
        tv_upversion_dialog_up.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (dialog != null) {
                    dialog.cancel();
//					initData2();
                }

//                requestMorePermissions1();
                checkUpdatePermission();


            }
        });
    }

    public void checkUpdatePermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            requestUpdatePermission();
        } else {
            UpdateManager manager = new UpdateManager(SplashActivity.this,
                    url);
            manager.showDownloadDialog();
        }
    }

    public void requestUpdatePermission() {
        String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

        ActivityCompat.requestPermissions(this, permissions, REQUEST_UPDATE);

    }


    // 启动应用的设置
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    /**
     * 获取手机的包管理者
     *
     * @return
     */
    public String getAppVersion() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            // 不可能发生.
            return "获取版本号失败";
        }
    }

    // 获取手机ip method-1
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        Toast.makeText(this,
                                inetAddress.getHostAddress().toString(), 3000)
                                .show();
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public String getMetaData(Context context) {

        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null && applicationInfo.metaData != null) {
                channel = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));

            }
        } catch (NameNotFoundException e) {
            throw new RuntimeException(
                    "you must set " + "" + " and " + "" + "  in your manifest file.", e);
        }

        return channel;
    }

    // 获取手机MAC地址
    /*
     * private String getMacAddress() { String result = ""; WifiManager
	 * wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	 * WifiInfo wifiInfo = wifiManager.getConnectionInfo(); result =
	 * wifiInfo.getMacAddress(); return result; }
	 */

}

